# 导入必要的库和模块
import gradio as gr
import pickle
from skimage.transform import resize
from sklearn.neighbors import KNeighborsClassifier
import numpy as np

# 加载保存的KNN模型
with open('E:/best_knn_model.pkl', 'rb') as file:
    knn = pickle.load(file)

# 定义预测函数
def preprocess(image):
    image=image.resize((8,8)).convert('L')
    image_array=np.array(image)
    flattened_image=image_array.ravel()
    return flattened_image

def predict(image):
    preprocess_image=preprocess(image)
    predicted_digit=knn.predict([preprocess_image])[0]
    return str(predicted_digit)

# 创建Gradio接口
iface = gr.Interface(predict, inputs=gr.Sketchpad(label="Image",brush_radius=5,type="pil",shape=(120,120)),
                     outputs=gr.Label("Guess"),
                     live=True,)

# 启动Gradio接口
iface.launch(share=True)
